package org.example.chatroom.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.chatroom.common.exception.ChatroomException;
import org.example.chatroom.common.pojo.dataobject.UserInfo;
import org.example.chatroom.common.pojo.request.LoginRequest;
import org.example.chatroom.common.pojo.request.RegisterRequest;
import org.example.chatroom.common.pojo.response.FriendResponse;
import org.example.chatroom.common.pojo.response.LoginResponse;
import org.example.chatroom.common.util.JWTUtils;
import org.example.chatroom.common.util.SecurityUtil;
import org.example.chatroom.mapper.UserMapper;
import org.example.chatroom.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LIUYANJIAO
 * Date: 2025-06-21
 * Time: 17:34
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    private static final Integer NORMAL_USER = 0;
    private static final Integer ABNORMAL_USER = 1;

    @Autowired
    private UserMapper userMapper;
    @Override
    public boolean register(RegisterRequest user) {
        user.setPassword(SecurityUtil.encrypt(user.getPassword()));
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(user,userInfo);
        Integer r= userMapper.insert(userInfo);
        if(r==1){
            return true;
        }
        else {
            throw new ChatroomException(401,"注册失败");
        }
    }

    @Override
    public LoginResponse login(LoginRequest user) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getDeleteFlag,NORMAL_USER)
                .eq(UserInfo::getTelephone,user.getTelephone());
        UserInfo userInfo = userMapper.selectOne(queryWrapper);
        if(userInfo==null||userInfo.getTelephone()==null){
            throw new ChatroomException(401,"登录失败");
        }
        if(!SecurityUtil.verify(user.getPassword(),userInfo.getPassword())){
            throw new ChatroomException(401,"密码错误");
        }
        //登录成功
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",userInfo.getId());
        claims.put("userName",userInfo.getUserName());
        claims.put("avatarUrl",userInfo.getAvatarUrl());
        String token = JWTUtils.genToken(claims);

        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setId(userInfo.getId());
        loginResponse.setToken(token);

        return loginResponse;
    }

}
